import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { request } from '../api/request';

// 数据项类型定义
export interface ImageCollectionItem {
  id?: number; // AI角色ID，可选字段
  avatar: string;
  username: string;
  imgsTotal: any;
  created_at: string;
  Images: string[];
  ai_person_id: any
}

// AI收藏数据类型定义
export interface AICollectionData {
  Images: string[];
  total_count: number;
}

// 排序选项类型
export type SortOption = 'newest' | 'oldest' | 'name';

// 排序选项配置
export const SORT_OPTIONS = [
  { key: 'newest' as const, labelKey: 'imageCollection.newestFirst' },
  { key: 'oldest' as const, labelKey: 'imageCollection.oldestFirst' },
  { key: 'name' as const, labelKey: 'imageCollection.alphabetical' }
];

/**
 * 图片收藏数据管理Hook
 */
export const useImageCollection = () => {
  const { i18n, t } = useTranslation();
  const [data, setData] = useState<ImageCollectionItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [sortBy, setSortBy] = useState<SortOption>('newest');
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);

  const LIMIT_PER_PAGE = 10;

  /**
   * 获取当前语言代码
   */
  const getCurrentLanguage = (): string => {
    const lang = i18n.language;
    if (lang.startsWith('zh')) return 'CN';
    if (lang.startsWith('ja')) return 'JP';
    return 'EN';
  };

  /**
   * 获取用户UUID
   */
  const getUserUuid = (): string | null => {
    try {
      const userData = localStorage.getItem('userData');
      if (!userData) return null;
      const parsedData = JSON.parse(userData);
      return parsedData.visitor_uuid || null;
    } catch (error) {
      // console.error('获取用户UUID失败:', error);
      console.error('get user uuid failed',error);
      return null;
    }
  };

  /**
   * 数据排序函数
   */
  const sortData = (data: ImageCollectionItem[], sortType: SortOption): ImageCollectionItem[] => {
    const sortedData = [...data];

    switch (sortType) {
      case 'newest':
        // 按创建时间降序排列（最新的在前）
        return sortedData.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());

      case 'oldest':
        // 按创建时间升序排列（最旧的在前）
        return sortedData.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());

      case 'name':
        // 按用户名字母顺序排列
        return sortedData.sort((a, b) => a.username.localeCompare(b.username));

      default:
        return sortedData;
    }
  };

  /**
   * 获取图片收藏数据
   */
  const fetchImageCollection = async (page: number = 1, isLoadMore: boolean = false) => {
    // 不要在普通函数内部调用useTranslation hook
    const uuid = getUserUuid();
    if (!uuid) {
      setError(t('collection.errors.userDataIncomplete'));
      return;
    }

    if (isLoadMore) {
      setLoadingMore(true);
    } else {
      setLoading(true);
      setError(null);
    }

    try {
      // console.log(`🔄 ${t('imageCollection.loading')}: ${page} / ${LIMIT_PER_PAGE}`);

      const response = await request.post('/api/ai-person-image/user-images', {
        uuid,
        language: getCurrentLanguage(),
        page,
        limit: LIMIT_PER_PAGE
      });

      if (response.data.success) {
        const newData = response.data.data || [];
        // console.log(`✅ ${t('collection.totalImages', { count: newData.length })}`);

        if (isLoadMore) {
          // 加载更多：合并数据
          setData(prevData => {
            const mergedData = [...prevData, ...newData];
            return sortData(mergedData, sortBy);
          });
        } else {
          // 初始加载：替换数据
          const sortedData = sortData(newData, sortBy);
          setData(sortedData);
        }

        // 判断是否还有更多数据
        if (newData.length < LIMIT_PER_PAGE) {
          setHasMore(false);
          // console.log(`📝 ${t('collection.allImagesLoaded')}`);
        } else {
          setHasMore(true);
        }

        // 更新当前页码
        setCurrentPage(page);
      } else {
        setError(response.data.message || t('collection.errors.loadFailed'));
      }
    } catch (err) {
      console.error(t('collection.errors.loadFailed'), err);
      setError(t('collection.errors.networkError'));
    } finally {
      if (isLoadMore) {
        setLoadingMore(false);
      } else {
        setLoading(false);
      }
    }
  };

  /**
   * 加载更多数据
   */
  const loadMore = useCallback(async () => {
    // 不要在回调函数内部调用useTranslation hook
    if (!hasMore || loadingMore || loading) {
      // console.log(`🚫 ${t('imageCollection.loadingMore')} ${t('common.cancel')}:`, { hasMore, loadingMore, loading });
      return;
    }

    const nextPage = currentPage + 1;
    // console.log(`🔄 ${t('imageCollection.loadingMore')}:`, nextPage);
    await fetchImageCollection(nextPage, true);
  }, [hasMore, loadingMore, loading, currentPage, sortBy]);

  /**
   * 更新排序方式
   */
  const updateSortBy = (newSortBy: SortOption) => {
    setSortBy(newSortBy);
    // 重新排序现有数据
    setData(prevData => sortData(prevData, newSortBy));
  };

  /**
   * 重置并重新加载数据
   */
  const refetch = useCallback(() => {
    setCurrentPage(1);
    setHasMore(true);
    setData([]);
    fetchImageCollection(1, false);
  }, [/* 依赖项应包含fetchImageCollection所需的状态，但由于它是内部函数，可以省略 */]);

  // 加载数据 - 初始化时和语言变化时
  useEffect(() => {
    refetch();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [i18n.language, refetch]);

  return {
    data,
    loading,
    loadingMore,
    error,
    sortBy,
    hasMore,
    updateSortBy,
    loadMore,
    refetch
  };
};